package com.xuecheng.test.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

public class Consumer04_Topics_SMS {
    // SMS队列
    private static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    // 交换机
    private static final String EXCHANGE_TOPICS_INFORM = "exchange_topics_inform";
    // 交换机key
    public static final String ROUTING_KEY_SMS = "inform.#.sms.#";

    public static void main(String[] args) {
        // 通过链接工程创建链接
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setVirtualHost("/");
        Connection connection = null;
        try {
            // 创建链接
            connection = connectionFactory.newConnection();
            // 创建通道
            Channel channel = connection.createChannel();
            // 指定目的地
            channel.queueDeclare(QUEUE_INFORM_SMS,true,false,false,null);
            // 声明交换机
            channel.exchangeDeclare(EXCHANGE_TOPICS_INFORM, BuiltinExchangeType.TOPIC);
            // 绑定路由key
            channel.queueBind(QUEUE_INFORM_SMS,EXCHANGE_TOPICS_INFORM,ROUTING_KEY_SMS);
            // 接收消息
            channel.basicConsume(QUEUE_INFORM_SMS,true,new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println("收到的消息==>" + new String(body, StandardCharsets.UTF_8));
                }
            });
        } catch (TimeoutException | IOException e) {
            e.printStackTrace();
        }
    }
}
